package br.com.wuo.genericInventary.application;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class Resources {
	public static final String BASE_DIR = ".genericinventary";
	public static final String DATA_DIR = "/data/";
	public static final String PROPERTIES_FILE = "genericinventary.properties";
	private static File baseDir;

	public static void verifyResources() throws FileNotFoundException {
		createBaseDir();
		createDirectory(DATA_DIR);
	}
	
	private static void createBaseDir() throws FileNotFoundException {
		if (baseDir == null) {
			baseDir = new File(System.getProperty("user.home"), BASE_DIR);
			if (!baseDir.exists()) {
				baseDir.mkdirs();
				setProperties(loadProperties());
			}
		}
	}
	
	private static Properties loadProperties(){
		
		Properties prop = new Properties();
		try {
			prop.load(Resources.class.getResourceAsStream("/genericinventary.properties"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return prop;
	}
	
	private static void createDirectory(String filePath) {
		File file = new File(baseDir, filePath);
		
		if (!file.exists()) {
			file.mkdirs();
		}
	}

	public static File getBaseDir() {
		return baseDir;
	}
	
	public static File getPropertiesFile() throws IOException {
		return new File(getBaseDir(), PROPERTIES_FILE);
	}
	
	public static void setProperties(Properties properties){
		String path = baseDir.getAbsolutePath() + "/" + PROPERTIES_FILE;
		try {
			properties.store(new FileOutputStream(path), null);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static Properties getProperties() {
		Properties properties = new Properties();
		
		try {
			FileInputStream in = new FileInputStream(getPropertiesFile());
			properties.load(in);
						
		} catch (IOException ioe) {
			ioe.printStackTrace();
			System.exit(1);
		}
		
		return properties;
	}

}
